package com.fc.happyteam.controller;

import com.fc.happyteam.entity.UserEntity;
import com.fc.happyteam.exception.ResponseException;
import com.fc.happyteam.utils.Constant;
import com.fc.happyteam.utils.SessionUtils;
import com.google.common.collect.Maps;

import java.util.Map;

public class BaseController {


	protected UserEntity getUser() {
		return SessionUtils.getUserEntity();
	}

	protected Long getUserId() {
		if(getUser() == null)
		{
			throw new ResponseException("用户未登录, 请重新登陆");
		}
		return getUser().getId();
	}

	protected Map<String, Object> calculatePagination(Map<String, Object> params) {
		if(params == null)
		{
			params = Maps.newHashMap();
		}

        if(params.get(Constant.DEFAULT_LIMIT_NAME) == null)
		{
			params.put(Constant.DEFAULT_LIMIT_NAME, Constant.DEFAULT_LIMIT);
		}
        if(params.get(Constant.DEFAULT_OFFSET_NAME) == null)
        {
            params.put(Constant.DEFAULT_OFFSET_NAME, Constant.DEFAULT_OFFSET);
        }

		int limit = (int)params.putIfAbsent(Constant.DEFAULT_LIMIT_NAME, Constant.DEFAULT_LIMIT);
		int offset = (int)params.putIfAbsent(Constant.DEFAULT_OFFSET_NAME, Constant.DEFAULT_OFFSET);
		params.put(Constant.DEFAULT_OFFSET_NAME, offset * limit);
		return params;
	}

	protected int calculateOffset(Integer offset, Integer limit)
	{
		if(offset == null)
		{
			offset = Constant.DEFAULT_OFFSET;
		}
		if(limit == null)
		{
			limit = Constant.DEFAULT_LIMIT;
		}
		return offset * limit;
	}
}
